<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="用户手机号" prop="userPhone">
              <el-input v-model="queryParams.userPhone" placeholder="请输入用户手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['shop:shopAdmin:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="shopAdminList">
        <el-table-column label="用户头像" align="center">
          <template #default="scope">
            <image-preview :src="scope.row.appUserVo.headPortrait" width="100px" height="80px"/>
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" align="center">
          <template #default="scope">
            {{scope.row.appUserVo.nickName}}
          </template>
        </el-table-column>
        <el-table-column label="用户手机号" align="center" prop="userPhone" />
<!--        <el-table-column label="店铺权限类型" align="center" prop="shopAuthType">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="shop_auth_type" :value="scope.row.shopAuthType" />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="角色信息" align="center">
          <template #default="scope">
            <div v-for="(shopRoleVo, index) in scope.row.roles" :key="index" style="margin-bottom: 5px">
              <el-tag type="success">{{shopRoleVo.roleName}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.shopAuthType != '1'">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['shop:shopAdmin:edit']">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.shopAuthType != '1'">
              <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['shop:shopAdmin:remove']">删除</el-button>
            </el-tooltip>
            <el-tooltip content="重置密码" placement="top">
              <el-button link type="danger" @click="openResetPasswordDialog(scope.row)" v-hasPermi="['shop:shopAdmin:edit']">重置密码</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改店铺管理员对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="30%" append-to-body>
      <el-form ref="shopAdminFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户手机号" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input show-password v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="form.id">
          <el-radio-group v-model="form.status">
            <el-radio v-for="(dict, index) in sys_normal_disable" :key="index" :value="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属角色" prop="shopRoleIdList">
          <el-select
            v-model="form.shopRoleIdList"
            multiple
            placeholder="请选择所属角色">
            <el-option
              v-for="(shopRole, index) in shopRoleList"
              :key="index"
              :label="shopRole.roleName + (shopRole.roleStatus == '0'?'':' 【已停用】')"
              :value="shopRole.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog :title="resetPasswordDialog.title" v-model="resetPasswordDialog.visible" width="30%" append-to-body>
      <el-form ref="resetPasswordFormRef" :model="resetPasswordForm" :rules="resetPasswordRules" label-width="100px">
        <el-form-item label="密码" prop="password">
          <el-input show-password v-model="resetPasswordForm.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="resetPasswordSubmit">重 置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopAdmin" lang="ts">
import { listShopAdmin, getShopAdmin, delShopAdmin, addShopAdmin, updateShopAdmin, resetPassword } from '@/api/system/shopAdmin';
import { queryShopRoleList } from '@/api/system/shopRole';
import { ShopAdminVO, ShopAdminQuery, ShopAdminForm } from '@/api/system/shopAdmin/types';
import { ShopRoleVO } from '@/api/system/shopRole/types';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { shop_auth_type, sys_normal_disable } = toRefs<any>(proxy?.useDict('shop_auth_type', 'sys_normal_disable'));

const shopAdminList = ref<ShopAdminVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const shopAdminFormRef = ref<ElFormInstance>();
const resetPasswordFormRef = ref<ElFormInstance>();

const shopRoleList = ref<ShopRoleVO[]>([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const resetPasswordDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShopAdminForm = {
  id: undefined,
  shopId: undefined,
  userId: undefined,
  userPhone: undefined,
  shopAuthType: undefined,
  password: undefined,
  salt: undefined,
  status: undefined,
  shopRoleIdList: [],
}
const data = reactive<PageData<ShopAdminForm, ShopAdminQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopId: undefined,
    userId: undefined,
    userPhone: undefined,
    shopAuthType: undefined,
    password: undefined,
    salt: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    shopId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    userPhone: [
      { required: true, message: "用户手机号不能为空", trigger: "blur" }
    ],
    shopAuthType: [
      { required: true, message: "店铺权限类型不能为空", trigger: "change" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    salt: [
      { required: true, message: "盐值不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    shopRoleIdList: [
      { required: true, message: "所属角色不能为空", trigger: "change" }
    ],
  }
});

const resetPasswordData = reactive({
  resetPasswordForm: {...initFormData},
  resetPasswordRules: {
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const { resetPasswordForm, resetPasswordRules } = toRefs(resetPasswordData);


/** 查询店铺管理员列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShopAdmin(queryParams.value);
  shopAdminList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  shopAdminFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加店铺管理员";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ShopAdminVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getShopAdmin(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改店铺管理员";
}

/** 提交按钮 */
const submitForm = () => {
  shopAdminFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateShopAdmin(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addShopAdmin(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ShopAdminVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除店铺管理员编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delShopAdmin(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/**
 * 查询店铺全部角色
 */
const queryShopRoleListData = async () => {
  const res = await queryShopRoleList();
  shopRoleList.value = res.data;
}

/**
 * 打开重置密码对话框
 */
const openResetPasswordDialog = (row: ShopAdminVO) => {
  resetPasswordData.resetPasswordForm.id = row.id;
  resetPasswordDialog.visible = true;
  resetPasswordDialog.title = "重置密码";
}

/**
 * 重置密码
 */
const resetPasswordSubmit = async () => {
  resetPasswordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await resetPassword(resetPasswordForm.value).finally(() =>  buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      resetPasswordDialog.visible = false;
      await getList();
    }
  });
}

onMounted(() => {
  getList();
  queryShopRoleListData();
});
</script>
